package com.elitesland.security.config;

import com.elitesland.security.service.entity.JwtUserDto;
import lombok.val;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * @author Mir
 * @date 3/17/2020
 */

public class SpringSecurityAuditorAware implements AuditorAware<String> {
    /**
     * 从SecurityContext中，获取当前登录用的用户ID
     *
     * @return 当前登录用户的用户ID
     */
    @Override
    public Optional<String> getCurrentAuditor() {
        try {
            val details = SecurityContextHolder.getContext().getAuthentication().getDetails();
            val user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (user instanceof JwtUserDto) {
                val u = (JwtUserDto) user;
                val nameStr = u.getUser().getFirstName() + ":" + u.getUser().getUsername();
                return Optional.of(nameStr);
            }
//            if (details instanceof Long) {
//                return Optional.of((Long) details);
//            }
        } catch (Exception e) {

        }
        return Optional.of("");
    }
}
